package stackdemo;

import java.util.Stack;

class MinStack {

    //因为要在常数时间内检索到最小元素，所以要设计两个栈，一个普通栈stack，一个最小栈minStack
    //minStack需要一直维护！！！
    //定义栈
    Stack<Integer> stack;
    Stack<Integer> minStack;

    //初始化栈
    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    //压栈
    public void push(int val) {
        stack.push(val);
        if(minStack.isEmpty()) {
            minStack.push(val);
        } else {
            int peekMinVal = minStack.peek();
            if(val <= peekMinVal) {
                minStack.push(val);
            }
        }
    }

    //出栈
    public void pop() {
        int val = stack.pop();
        if(val == minStack.peek()) {
            minStack.pop();
        }
    }

    //就是peek
    public int top() {
        return stack.peek();
    }

    //获取最小元素  时间复杂度为O(1)
    public int getMin() {
        return minStack.peek();
    }
}
